import { useState } from 'react';

export const useJsonTable = () => {
  const [jsonInput, setJsonInput] = useState('');
  const [tableData, setTableData] = useState<{ headers: string[]; rows: any[] } | null>(null);
  const [error, setError] = useState('');

  // Parse JSON input and transform it into table data
  const parseJson = () => {
    if (!jsonInput.trim()) {
      setError('请输入JSON数据');
      setTableData(null);
      return;
    }

    try {
      const parsed = JSON.parse(jsonInput);

      // Handle different data structures
      if (Array.isArray(parsed)) {
        if (parsed.length === 0) {
          setError('JSON数组为空');
          setTableData(null);
          return;
        }

        // Array of objects
        if (typeof parsed[0] === 'object' && parsed[0] !== null) {
          const headers = Array.from(
            new Set(parsed.flatMap(item => Object.keys(item)))
          );
          const rows = parsed.map(item => 
            headers.map(header => {
              const value = item[header];
              return typeof value === 'object' ? JSON.stringify(value) : value;
            })
          );
          setTableData({ headers, rows });
          setError('');
        } 
        // Array of primitives
        else {
          setTableData({
            headers: ['值'],
            rows: parsed.map(item => [item])
          });
          setError('');
        }
      } 
      // Single object
      else if (typeof parsed === 'object' && parsed !== null) {
        const headers = Object.keys(parsed);
        const rows = [
          headers.map(key => {
            const value = parsed[key];
            return typeof value === 'object' ? JSON.stringify(value) : value;
          })
        ];
        setTableData({ headers, rows });
        setError('');
      } 
      // Single primitive
      else {
        setTableData({
          headers: ['值'],
          rows: [[parsed]]
        });
        setError('');
      }
    } catch (err) {
      setError('JSON格式错误');
      setTableData(null);
    }
  };

  // Copy table as CSV
  const copyAsCSV = () => {
    if (!tableData) return false;
    
    const { headers, rows } = tableData;
    const csvContent = [
      headers.join(','),
      ...rows.map(row => 
        row.map((cell: any) => 
          typeof cell === 'string' ? `"${cell.replace(/"/g, '""')}"` : cell
        ).join(',')
      )
    ].join('\n');
    
    navigator.clipboard.writeText(csvContent);
    return true;
  };

    // Copy table as CSV
    const copyAsExcel = () => {
        if (!tableData) return false;
        
        const { headers, rows } = tableData;
        const csvContent = [
          headers.join('\t'),
          ...rows.map(row => 
            row.join('\t')
          )
        ].join('\n');
        
        navigator.clipboard.writeText(csvContent);
        return true;
      };

  // Copy table as Markdown
  const copyAsMarkdown = () => {
    if (!tableData) return false;
    
    const { headers, rows } = tableData;
    const markdownContent = [
      `| ${headers.join(' | ')} |`,
      `| ${headers.map(() => '---').join(' | ')} |`,
      ...rows.map(row => 
        `| ${row.map((cell: any) => cell !== null && cell !== undefined ? String(cell) : '').join(' | ')} |`
      )
    ].join('\n');
    
    navigator.clipboard.writeText(markdownContent);
    return true;
  };

  // Copy table as HTML
  const copyAsHTML = () => {
    if (!tableData) return false;
    
    const { headers, rows } = tableData;
    const htmlContent = `
<table>
  <thead>
    <tr>
      ${headers.map(header => `<th>${header}</th>`).join('\n      ')}
    </tr>
  </thead>
  <tbody>
    ${rows.map(row => `
    <tr>
      ${row.map((cell: any) => `<td>${cell !== null && cell !== undefined ? String(cell) : ''}</td>`).join('\n      ')}
    </tr>`).join('\n    ')}
  </tbody>
</table>`;
    
    navigator.clipboard.writeText(htmlContent);
    return true;
  };

  // Load example data
  const loadExample = () => {
    setJsonInput(`[
  {
    "id": 1,
    "name": "张三",
    "age": 28,
    "department": "技术部",
    "skills": ["JavaScript", "React", "Node.js"]
  },
  {
    "id": 2,
    "name": "李四",
    "age": 32,
    "department": "市场部",
    "skills": ["营销", "数据分析"]
  },
  {
    "id": 3,
    "name": "王五",
    "age": 25,
    "department": "设计部",
    "skills": ["UI设计", "UX设计", "Figma"]
  }
]`);
  };

  return {
    jsonInput,
    setJsonInput,
    tableData,
    error,
    parseJson,
    copyAsCSV,
    copyAsMarkdown,
    copyAsHTML,
    loadExample,
    copyAsExcel
  };
}; 